package com.wumz.netty.tomcat.nio.handler;

import com.wumz.netty.tomcat.nio.http.MyRequest;
import com.wumz.netty.tomcat.nio.http.MyResponse;
import com.wumz.netty.tomcat.nio.http.MyServlet;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.HttpRequest;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by wumz on 2021/3/12 9:59
 */
public class BusinessHandler extends ChannelInboundHandlerAdapter {

    private Map<String, MyServlet> servletMapping = new HashMap<>();

    public BusinessHandler(Map<String, MyServlet> servletMapping){
        this.servletMapping = servletMapping;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if(msg instanceof HttpRequest){
            HttpRequest req = (HttpRequest) msg;

            MyRequest request = new MyRequest(ctx,req);
            MyResponse response = new MyResponse(ctx,req);

            String url = request.getUrl();

            if(servletMapping.containsKey(url)){
                servletMapping.get(url).service(request,response);
            }else{
                response.write("404 - Not Found!!");
            }

        }
    }
}
